import { defineStore } from 'pinia';
import { local } from '@/utils/storage';
import { IMultipleTabs } from '@/store/types';
import { store } from '@/store';

export const MULTIPLE_TABS = 'multiple_tabs';

const defaultMultipleTabs = local.get<IMultipleTabs[]>(MULTIPLE_TABS, []);
export const useMultipleTabs = defineStore(MULTIPLE_TABS, {
  state: (): { data: IMultipleTabs[] } => ({ data: defaultMultipleTabs }),
  actions: {
    /**
     * 添加一个标签
     * @param tab
     */
    addTab(tab: IMultipleTabs) {
      if (tab.title === '404') {
        return;
      }
      const isExist = this.data.findIndex((value) => {
        return value.name === tab.name;
      });
      if (isExist === -1) {
        this.data.push(tab);
      }
    },
    /**
     * 删除一个标签
     * @param name
     */
    removeTab(name: string) {
      this.data = this.data.filter((value) => {
        return value.name !== name;
      });
    },
    /**
     * 清空所有标签
     */
    clearTabs() {
      this.data = [];
    },
    /**
     * 关闭当前标签左边的所有标签
     * @param name
     */
    closeBeforeTabs(name: string) {
      const currentIndex = this.data.findIndex((value) => {
        return value.name === name;
      });
      if (currentIndex === -1) {
        return;
      }
      this.data = this.data.slice(currentIndex, this.data.length);
    },
    /**
     * 关闭当前标签右边的所有标签
     * @param name
     */
    closeAfterTabs(name: string) {
      const currentIndex = this.data.findIndex((value) => {
        return value.name === name;
      });
      if (currentIndex === -1) {
        return;
      }
      this.data = this.data.slice(0, currentIndex + 1);
    },
    /**
     * 关闭当前标签外的所有标签
     * @param name
     */
    closeOtherTabs(name: string) {
      const currentVale = this.data.find((value) => {
        return value.name === name;
      });
      this.data = [currentVale!];
    },
    initStore() {},
  },
});

/**
 * 在setup外使用本商店
 */
export const useMultipleTabsStoreWithOut = () => {
  return useMultipleTabs(store);
};

const initStore = useMultipleTabsStoreWithOut();
initStore.$subscribe((mutation, state) => {
  local.set(mutation.storeId, JSON.stringify(state.data));
});
